﻿/******************************************************************************
 *  作者：       Maxzhang1985
 *  创建时间：   2012/4/18 9:41:33
 *
 *
 ******************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExtendPropertyLib.WPF;
using ExtendPropertyLib;
using ExORMDesginer.Models;
using System.IO;
using ExORMDesginer.Helper;
using System.ComponentModel.Composition;
using ExORMDesginer.Plugin;
using ExORMDesginer.Services;
using ExORMDesginer.Plugin.Template;
namespace ExORMDesginer.UserControls
{
    /// <summary>
    /// 代码生成器业务器
    /// </summary>
    public class CodeGeneratorInfo : BusinessInfoBase<CodeGeneratorInfo>
    {
        
        public static ExtendProperty TemplateListProperty = RegisterProperty(v => v.TemplateList);
        /// <summary>
        /// 模板列表
        /// </summary>
        public SerializableObservableCollection<TemplateInfo> TemplateList { set { SetValue(TemplateListProperty, value); } get { return (SerializableObservableCollection<TemplateInfo>)GetValue(TemplateListProperty); } }

        #region FIle BasePath
        
        private static string basePath = AppDomain.CurrentDomain.BaseDirectory;
        private static string templatePath = Path.Combine(basePath, "ItemTemplate");
        private static string configPath = Path.Combine(templatePath, "TemplateCfg.xml");
        #endregion

        private void loadTemplateList()
        {
            string configXml = File.ReadAllText(configPath, Encoding.Default);
            TemplateList = configXml.Deserialize<SerializableObservableCollection<TemplateInfo>>();
        }

        [ImportMany(typeof(IWizard))]
        private List<IWizard> WizardList { set; get; }


        public override void OnLoad()
        {
            loadTemplateList();
        }

        public void SaveTemplate()
        {
            string cfgXml = TemplateList.Serializer();
            File.WriteAllText(configPath,cfgXml,Encoding.Default);
        }

        public string LoadTemplate(TemplateInfo info)
        {
            var templateFile = Path.Combine(templatePath, info.FileName);
            return File.ReadAllText(templateFile, Encoding.Default);
        }

        /// <summary>
        /// 根据模板和设计向导生成代码
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        public string GeneratorCode(TemplateInfo info,DbEntity entity)
        {
            if (info != null)
            {
                IWizard wizard = WizardList.FirstOrDefault(w => w.Name == info.WizardName);
                wizard.Host = MasterHost.Instance;
                wizard.TemplateInfo = info;
                wizard.Model = entity;
                return wizard.Process();
            }
            return "";
        }
    }
}
